<template>
  <div v-if="!authSuccess">
    <div class="reset-title">{{ handle.resetTip }}</div>
    <div
      v-if="!resetPasswordStatus"
      class="auth-box"
      :style="{
        width: configOption.scheme == loginPlan.MARK_LOGIN_LOGINMETHOD_1 ? '360px' : '360px',
      }"
    >
      <div :class="{ 'force-div': validaErrorStatus.phone }">
        <je-input
          v-model:value="userAuth.phone"
          :placeholder="handle.phonePlace"
          :maxlength="11"
          class="input-item"
          :style="{
            height: configOption.scheme == loginPlan.MARK_LOGIN_LOGINMETHOD_1 ? '46px' : '46px',
            'line-height':
              configOption.scheme == loginPlan.MARK_LOGIN_LOGINMETHOD_1 ? '46px' : '46px',
            border: validaErrorStatus.phone ? '1px solid #ff625c' : '',
          }"
          @change="changeInfo('phone')"
          @blur="changeInfo('phone')"
        >
          <template #prefix>
            <i class="fal fa-tablet-android-alt" style="padding-right: 5px"></i>
          </template>
        </je-input>
      </div>
      <div :class="{ 'force-div': validaErrorStatus.authCode }">
        <je-input
          v-model:value="userAuth.authCode"
          :placeholder="handle.codePlace"
          class="input-item"
          :style="{
            'margin-top':
              configOption.scheme == loginPlan.MARK_LOGIN_LOGINMETHOD_1 ? '30px' : '30px',
            height: configOption.scheme == loginPlan.MARK_LOGIN_LOGINMETHOD_1 ? '46px' : '46px',
            'line-height':
              configOption.scheme == loginPlan.MARK_LOGIN_LOGINMETHOD_1 ? '46px' : '46px',
            border: validaErrorStatus.authCode ? '1px solid #ff625c' : '',
          }"
          @change="changeInfo('authCode')"
          @blur="changeInfo('authCode')"
        >
          <template #prefix>
            <i class="jeicon jeicon-key" style="padding-right: 5px"></i>
          </template>
          <template #suffix>
            <span
              :class="{ 'auth-code': sendCodeStatus, 'auth-time': !sendCodeStatus }"
              @click="sendAuthCode"
              >{{ sendCodeStatus ? handle.getAuthCode : sendCountdown + 's' }}</span
            >
          </template>
        </je-input>
      </div>

      <div
        class="err-tip"
        :style="{
          'margin-top': configOption.scheme == loginPlan.MARK_LOGIN_LOGINMETHOD_1 ? '40px' : '40px',
        }"
      >
        {{ errMessage }}
      </div>
      <je-button block class="opera-btn" @click="handleNext">
        {{ handle.nextBut }}
      </je-button>
    </div>
    <div v-if="resetPasswordStatus">
      <div class="rule-prompt">{{ passwordRuleTip }}</div>
      <div class="reset-box">
        <div :class="{ 'force-div': validaErrorStatus.newPassword }">
          <je-password
            v-model:value="userSet.newPassword"
            :placeholder="handle.newPassword"
            class="input-item"
            :style="{ border: validaErrorStatus.newPassword ? '1px solid #ff625c' : '' }"
            @change="changeInfo('newPassword')"
            @blur="changeInfo('newPassword')"
          >
            <template #prefix>
              <i class="fal fa-lock" style="padding-right: 5px"></i>
            </template>
          </je-password>
        </div>
        <div class="auth-stren-box">
          <div class="stren-tip">{{ passwordRule }}</div>
          <div class="stren-progre">
            <div
              class="progre-item"
              :class="{
                'progre-part': ruleStepOne,
                'progre-all': ruleStepOne && ruleStepTwo && ruleStepThree,
              }"
            ></div>
            <div
              class="progre-item"
              :class="{
                'progre-part': ruleStepOne && ruleStepTwo,
                'progre-all': ruleStepOne && ruleStepTwo && ruleStepThree,
              }"
            ></div>
            <div
              class="progre-item"
              :class="{
                'progre-all': ruleStepOne && ruleStepTwo && ruleStepThree,
              }"
            ></div>
          </div>
        </div>
        <div :class="{ 'force-div': validaErrorStatus.confirmPassword }">
          <je-password
            v-model:value="userSet.confirmPassword"
            :placeholder="handle.confirmPassword"
            class="input-item"
            :style="{ border: validaErrorStatus.confirmPassword ? '1px solid #ff625c' : '' }"
            @change="changeInfo('confirmPassword')"
            @blur="changeInfo('confirmPassword')"
          >
            <template #prefix>
              <i class="fal fa-lock" style="padding-right: 5px"></i>
            </template>
          </je-password>
        </div>
        <div class="anth-error">{{ anthErrorMes }}</div>
        <je-button block class="opera-btn" @click="handleSubmit">
          {{ handle.submitBut }}
        </je-button>
      </div>
    </div>
  </div>
  <div v-if="authSuccess" class="auth-success">
    <div class="auth-icon">
      <i class="jeicon jeicon-check-circle-s"></i>
    </div>
    <div class="success-tip">{{ handle.resetSuccess }}</div>
  </div>

  <div ref="backLoginRef" class="back-login" @click="handleBackLogin">{{ handle.backLogin }}</div>
</template>

<script>
  import { defineComponent, reactive, ref, toRefs, nextTick, onMounted, onUnmounted } from 'vue';
  import VueEvent from '@/helper/event';
  import { useI18n } from '@common/locales';
  import { Input, Button } from '@jecloud/ui';
  import {
    LOGIN_PLAN,
    EVENT_METHOD,
    LOGIN_DEVICE,
    SEND_CODE_TIMES,
    PASSWORD_SAFE_STRATEGY,
    CUR_PAGE,
  } from '@/helper/constant';
  import {
    loginValidaPhone,
    passwordSimpleRegTempalte,
    passwordMedinmRegTempalte,
    passwordSimpleComplexTempalte,
    containsNumber,
    constainsLetter,
    constainsChars,
    constainsNumberAndChars,
    constainsNumberAndLetter,
    constainsLetterAndChars,
    constainsLowerLetterAndCharNum,
    constainsLargeLetterAndCharsNum,
  } from '@/helper/publish';
  import { LoginSendCode, ForgetResetPassword, CheckCaptcha } from '@/api';
  export default defineComponent({
    name: 'ResetPassword',
    components: {
      JeInput: Input,
      JeButton: Button,
      JePassword: Input.Password,
    },
    setup() {
      const t = useI18n().t;
      let configOption = ref({ scheme: LOGIN_PLAN.MARK_LOGIN_LOGINMETHOD_1 });
      let sendCodeStatus = ref(true); //验证码发送状态
      let authCodeTimeout = SEND_CODE_TIMES; //验证码失效时间，默认60s
      let sendCountdown = ref(authCodeTimeout);
      let resetPasswordStatus = ref(false); //是否为密码设置阶段
      let anthErrorMes = ref(''); //验证错误信息
      let authSuccess = ref(false); //验证成功状态
      let errMessage = ref(''); //错误信息提示
      let passwordRule = ref(t('resetPassword.stepNull')); //输入密码规则提示
      let ruleStepOne = ref(false); //密码验证第一步
      let ruleStepTwo = ref(false); //密码验证第二步
      let ruleStepThree = ref(false); //密码验证第三步
      let backLoginRef = ref(null); //返回登录按钮对象
      let passwordRuleTip = ref(''); //密码安全策略提示
      let handleFlag = true; //操作标识符
      let pl = 6; //输入新密码长度
      const userSet = reactive({
        //用户设置新密码
        newPassword: '',
        confirmPassword: '',
      });
      const userAuth = reactive({
        //用户验证码
        phone: '',
        authCode: '',
      });
      //验证错误状态
      const validaErrorStatus = reactive({
        phone: false,
        authCode: false,
        newPassword: false,
        confirmPassword: false,
      });
      let sentObj = {
        //发送验证码定时器
        sentCodeTimer: null,
        sentCodeTime: 1000,
      };
      const state = {
        eventMethod: EVENT_METHOD,
        loginPlan: LOGIN_PLAN,
        isNext: false, //是否点击下一步
        isSubmit: false, //是否点击提交
        handle: {
          resetTip: t('resetPassword.resetTip'),
          phonePlace: t('resetPassword.phonePlace'),
          codePlace: t('resetPassword.codePlace'),
          getAuthCode: t('accountLogin.getAuthCode'),
          nextBut: t('resetPassword.nextBut'),
          submitBut: t('resetPassword.submitBut'),
          backLogin: t('resetPassword.backLogin'),
          newPassword: t('resetPassword.newPassword'),
          confirmPassword: t('resetPassword.confirmPassword'),
          stepNull: t('resetPassword.stepNull'),
          stepOne: t('resetPassword.stepOne'),
          stepTwo: t('resetPassword.stepTwo'),
          stepThree: t('resetPassword.stepThree'),
          resetSuccess: t('resetPassword.resetSuccess'),
          emptyPhone: t('warnMessage.phone'),
          emptyAuthCode: t('warnMessage.authCode'),
          formatPhone: t('warnMessage.formatPhone'),
          emptyNewPassword: t('warnMessage.newPassword'),
          emptyConfirmPassword: t('warnMessage.confirmPassword'),
          fromatNewPassword: t('warnMessage.fromatNewPassword'),
        },
      };

      const methods = {
        triggerConfig(data) {
          nextTick(() => {
            //监听登录页面配置信息
            configOption.value = { ...data };
            pl = parseInt(data.REGEXP_NUMBER);
            passwordRuleTip.value = `密码为${pl}位以上${PASSWORD_SAFE_STRATEGY[data.REGEXP]}`;
            authCodeTimeout = parseInt(data.JE_SMS_TIMEOUT);
            sendCountdown.value = authCodeTimeout;
          });
        },
        changeInfo(type) {
          switch (type) {
            case 'phone': //监听手机号
              if (userAuth.phone) {
                errMessage.value = '';
                validaErrorStatus.phone = false;
              } else {
                errMessage.value = state.handle.emptyPhone;
                validaErrorStatus.phone = true;
              }
              break;
            case 'authCode': //监听验证码
              if (userAuth.phone) {
                if (userAuth.authCode) {
                  errMessage.value = '';
                  validaErrorStatus.authCode = false;
                } else {
                  errMessage.value = state.handle.emptyAuthCode;
                  validaErrorStatus.authCode = true;
                }
              }
              break;
            case 'newPassword': //监听新密码
              if (userSet.newPassword) {
                anthErrorMes.value = '';
                validaErrorStatus.newPassword = false;
              } else {
                anthErrorMes.value = state.handle.emptyNewPassword;
                validaErrorStatus.newPassword = true;
              }
              if (userSet.newPassword.length >= pl) {
                if (passwordSimpleComplexTempalte(pl).test(userSet.newPassword)) {
                  ruleStepOne.value = true;
                  ruleStepTwo.value = true;
                  ruleStepThree.value = true;
                  passwordRule.value = state.handle.stepThree;
                  return;
                } else if (passwordMedinmRegTempalte(pl).test(userSet.newPassword)) {
                  ruleStepOne.value = true;
                  ruleStepTwo.value = true;
                  ruleStepThree.value = false;
                  passwordRule.value = state.handle.stepTwo;
                  return;
                } else if (passwordSimpleRegTempalte(pl).test(userSet.newPassword)) {
                  ruleStepOne.value = true;
                  ruleStepTwo.value = false;
                  ruleStepThree.value = false;
                  passwordRule.value = state.handle.stepOne;
                  return;
                } else if (containsNumber(userSet.newPassword)) {
                  ruleStepOne.value = true;
                  ruleStepTwo.value = false;
                  ruleStepThree.value = false;
                  passwordRule.value = t('resetPassword.noneLetter');
                  return;
                } else if (constainsLetter(userSet.newPassword)) {
                  ruleStepOne.value = true;
                  ruleStepTwo.value = false;
                  ruleStepThree.value = false;
                  passwordRule.value = t('resetPassword.noneNumber');
                  return;
                } else if (constainsChars(userSet.newPassword)) {
                  ruleStepOne.value = true;
                  ruleStepTwo.value = false;
                  ruleStepThree.value = false;
                  passwordRule.value = t('resetPassword.noneNumber');
                  return;
                } else if (constainsNumberAndChars(userSet.newPassword)) {
                  ruleStepOne.value = true;
                  ruleStepTwo.value = true;
                  ruleStepThree.value = false;
                  passwordRule.value = t('resetPassword.noneLetter');
                  return;
                } else if (constainsLetterAndChars(userSet.newPassword)) {
                  ruleStepOne.value = true;
                  ruleStepTwo.value = true;
                  ruleStepThree.value = false;
                  passwordRule.value = t('resetPassword.noneNumber');
                  return;
                } else if (constainsNumberAndLetter(userSet.newPassword)) {
                  ruleStepOne.value = true;
                  ruleStepTwo.value = true;
                  ruleStepThree.value = false;
                  passwordRule.value = t('resetPassword.noneLetter');
                  return;
                } else if (constainsLargeLetterAndCharsNum(userSet.newPassword)) {
                  ruleStepOne.value = true;
                  ruleStepTwo.value = true;
                  ruleStepThree.value = false;
                  passwordRule.value = t('resetPassword.noneLetter');
                  return;
                } else if (constainsLowerLetterAndCharNum(userSet.newPassword)) {
                  ruleStepOne.value = true;
                  ruleStepTwo.value = true;
                  ruleStepThree.value = false;
                  passwordRule.value = t('resetPassword.noneLetter');
                  return;
                }
              } else {
                passwordRule.value = state.handle.stepNull;
                ruleStepOne.value = false;
                ruleStepTwo.value = false;
                ruleStepThree.value = false;
              }
              break;
            case 'confirmPassword': //监听确认密码
              if (userSet.newPassword) {
                if (userSet.confirmPassword) {
                  anthErrorMes.value = '';
                  validaErrorStatus.confirmPassword = false;
                } else {
                  anthErrorMes.value = state.handle.emptyConfirmPassword;
                  validaErrorStatus.confirmPassword = true;
                }
              }
              break;
            default:
              break;
          }
        },
        sendAuthCode() {
          //获取验证码
          if (!userAuth.phone) {
            errMessage.value = state.handle.emptyPhone;
            return;
          } else {
            if (!loginValidaPhone.test(userAuth.phone)) {
              errMessage.value = state.handle.formatPhone;
              return;
            }
          }
          if (sendCodeStatus.value) {
            LoginSendCode({
              phone: userAuth.phone,
              device: LOGIN_DEVICE,
            }).then((res) => {
              if (res.code == 1000 && res.success) {
                sendCodeStatus.value = !sendCodeStatus.value;
                if (sentObj.sentCodeTimer) {
                  clearInterval(sentObj.sentCodeTimer);
                }
                sentObj.sentCodeTimer = setInterval(() => {
                  sendCountdown.value -= 1;
                  if (sendCountdown.value === 0) {
                    sendCountdown.value = authCodeTimeout;
                    clearInterval(sentObj.sentCodeTimer);
                    sendCodeStatus.value = true;
                  }
                }, sentObj.sentCodeTime);
              } else {
                errMessage.value = res.message;
              }
            });
          }
        },
        resetState() {
          //重置数据
          state.isNext = false;
          resetPasswordStatus.value = false;
          errMessage.value = '';
          anthErrorMes.value = '';
          userSet.newPassword = '';
          userSet.confirmPassword = '';
          userAuth.phone = '';
          userAuth.authCode = '';
          sendCountdown.value = authCodeTimeout;
          sendCodeStatus.value = true;
          for (let key in validaErrorStatus) {
            validaErrorStatus[key] = false;
          }
        },
        handleBackLogin() {
          //返回登录
          sendCodeStatus.value = false;
          authSuccess.value = false;
          methods.resetState();
          VueEvent.emit(state.eventMethod.FORGET_PASSWORD);
        },
        handleNext() {
          //下一步
          state.isNext = true;
          if (!userAuth.phone) {
            errMessage.value = state.handle.emptyPhone;
            validaErrorStatus.phone = true;
            return;
          } else {
            if (!loginValidaPhone.test(userAuth.phone)) {
              errMessage.value = state.handle.formatPhone;
              return;
            }
            validaErrorStatus.phone = false;
          }
          if (!userAuth.authCode) {
            errMessage.value = state.handle.emptyAuthCode;
            validaErrorStatus.authCode = true;
            return;
          } else {
            validaErrorStatus.authCode = false;
          }
          //动态密码登录
          if (handleFlag) {
            handleFlag = false;
            CheckCaptcha({
              phone: userAuth.phone,
              captcha: userAuth.authCode,
              device: LOGIN_DEVICE,
            }).then((res) => {
              handleFlag = true;
              if (res.code == '1000' && res.success) {
                resetPasswordStatus.value = true;
              } else {
                errMessage.value = res.message;
              }
            });
          }
        },
        handleSubmit() {
          //提交
          state.isSubmit = true;
          if (userSet.newPassword == '') {
            anthErrorMes.value = state.handle.emptyNewPassword;
            validaErrorStatus.newPassword = true;
            return;
          } else {
            validaErrorStatus.newPassword = false;
          }
          if (!userSet.confirmPassword) {
            anthErrorMes.value = state.handle.emptyConfirmPassword;
            validaErrorStatus.confirmPassword = true;
            return;
          } else {
            validaErrorStatus.confirmPassword = false;
          }
          if (userSet.newPassword !== userSet.confirmPassword) {
            anthErrorMes.value = state.handle.fromatNewPassword;
            return;
          }
          if (handleFlag) {
            handleFlag = false;
            ForgetResetPassword({
              newPassword: userSet.newPassword,
              confirmPassword: userSet.confirmPassword,
              device: LOGIN_DEVICE,
              phone: userAuth.phone,
              captcha: userAuth.authCode,
            }).then((res) => {
              handleFlag = true;
              if (res.code == 1000 && res.success) {
                anthErrorMes.value = '';
                authSuccess.value = true;
              } else {
                anthErrorMes.value = res.data;
              }
            });
          }
        },
        keyEnterDown(event) {
          if (sessionStorage.getItem(CUR_PAGE.temPage) === CUR_PAGE.forgetPage) {
            const e = event || window.event;
            if (e && e.keyCode === 13) {
              e.preventDefault();
              if (!authSuccess.value) {
                methods.handleNext();
              } else {
                methods.handleSubmit();
              }
            }
          }
        },
      };

      onMounted(() => {
        //监听事件
        VueEvent.on(state.eventMethod.LOGIN_METHOD, methods.triggerConfig);
        VueEvent.on(state.eventMethod.FORGET_PASSWORD, methods.resetState);
        document.addEventListener('keydown', methods.keyEnterDown);
      });
      onUnmounted(() => {
        document.addEventListener('keydown', null);
      });
      return {
        configOption,
        sendCodeStatus,
        sendCountdown,
        resetPasswordStatus,
        anthErrorMes,
        authSuccess,
        userSet,
        userAuth,
        errMessage,
        validaErrorStatus,
        passwordRule,
        ruleStepOne,
        ruleStepTwo,
        ruleStepThree,
        backLoginRef,
        passwordRuleTip,
        ...toRefs(state),
        ...methods,
      };
    },
  });
</script>
<style>
  .input-item .ant-input-clear-icon {
    top: 12px !important;
  }
</style>
<style scoped lang="less">
  .reset-title {
    width: 100%;
    height: 20px;
    line-height: 20px;
    text-align: center;
    color: #3f3f3f;
    font-size: 20px;
    font-family: 'PingFang SC, PingFang SC-Normal';
  }
  .rule-prompt {
    width: 100%;
    height: 20px;
    line-height: 20px;
    text-align: center;
    color: #c0c4cc;
    font-size: 14px;
    margin-top: 10px;
  }
  .auth-box {
    width: 360px;
    margin: 30px auto 0;
  }
  .input-item {
    border-radius: 2px;
    font-size: 12px;
    color: #a1a1a1;
    line-height: 46px;
    height: 46px;
  }
  .auth-code {
    font-size: 14px;
    color: #3265f5;
    cursor: pointer;
  }
  .auth-time {
    font-size: 14px;
    color: #c0c4cc;
  }
  .opera-btn {
    height: 42px;
    margin-top: 10px;
    font-size: 18px;
    color: #ffffff;
    line-height: 20px;
  }
  .submit-btn {
    height: 42px;
    margin-top: 10px;
    font-size: 18px;
    color: #ffffff;
    line-height: 20px;
  }
  .opera-btn:hover,
  .submit-btn:hover {
    color: #fff !important;
    border-color: transparent !important;
  }
  .back-login {
    width: 20%;
    height: 20px;
    line-height: 20px;
    text-align: center;
    color: #3f3f3f;
    font-size: 14px;
    margin: 30px auto 0;
    cursor: pointer;
  }
  .reset-box {
    width: 360px;
    margin: 20px auto 0;
  }
  .auth-stren-box {
    width: 100%;
    padding-left: 12px;
    .stren-tip {
      height: 12px;
      font-size: 12px;
      line-height: 12px;
      color: #c0c4cc;
      margin-top: 10px;
    }
    .stren-progre {
      display: flex;
      margin: 6px auto 10px;
      .progre-item {
        width: 50px;
        height: 4px;
        background: #a9aba9;
        margin-right: 6px;
      }
      .progre-part {
        background: #f9a646;
      }
      .progre-all {
        background: #02a863;
      }
    }
  }
  .anth-error {
    width: 100%;
    height: 20px;
    line-height: 20px;
    font-size: 14px;
    color: #ff625c;
    text-align: center;
    margin-top: 30px;
  }
  .auth-success {
    width: 360px;
    margin: 10px auto 0;
    .auth-icon {
      width: 50px;
      height: 50px;
      margin: 0 auto;
      position: relative;
      i {
        font-size: 50px;
        color: #6dcc51;
        position: absolute;
        top: -14px;
      }
    }
    .success-tip {
      width: 100%;
      height: 20px;
      line-height: 20px;
      font-size: 20px;
      color: #3f3f3f;
      text-align: center;
      margin-top: 20px;
    }
  }
  .err-tip {
    width: 100%;
    height: 20px;
    margin-top: 40px;
    line-height: 20px;
    font-size: 14px;
    color: #ff625c;
    text-align: center;
  }
</style>
